<?php

namespace App\Http\Controllers\Api;

use App\Libs\Util;
use App\Libs\WeChat\WxSmallClient;
use App\Models\e_class;
use App\Models\e_user_class_record;
use App\Models\e_user_info_likes;
use App\Models\e_user_note_info;
use App\Models\punch_comments;
use App\Models\user;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use League\Flysystem\Exception;

class ClassController extends Controller
{

    public $bonus = '';
    public function __construct(Request $request)
    {
        /*$openid = $request->openid;
        //获取用户信息
        $user_info = Redis::get('punch_user_info'.$openid);
        if(!$user_info){
            fun_respon(0, '缺少用户信息!');
        }
        $user_info = json_decode($user_info,true);
        $this->bonus = $user_info['bonus'];*/
    }


    public function gettestuser(Request $request){
        $openid = $request->openid;
        //获取用户信息
        $user_info = Redis::get('punch_user_info'.$openid);
        if(!$user_info){
            fun_respon(0, '缺少用户信息!');
        }
        $user_info = json_decode($user_info,true);
        $this->bonus = $user_info['bonus'];
    }

    private $pageSize = 10;
    /**
     * 打卡列表
     * @param Request $request
     */
    public function address(Request $request)
    {
        $openid = $request->openid;
        $page = $request->json('page',1);
        $list = address::lists($openid, $page);
        fun_respon(1, $list);
    }

    /**
     * 添加打卡
     */
    public function addPunch(Request $request)
    {
            $openid = $request->openid;
            $params = $request->only(['title','punch_image','content','status']);
            if (empty($params['title'])) {
                fun_respon(0, '缺少参数');
            }
            $params['user_id'] = $openid;
            $params['punch_image'] = $params['punch_image']?$params['punch_image']:'';
            $params['content'] = $params['content']?$params['content']:'';
            $params['status'] = $params['status']?$params['status']:1;
            $params['is_valid'] = 0;
            $res = punch_activity::insertGetId($params);
            $params['id'] = $res;
            if($res){
                fun_respon(1, $params);
            }
            fun_respon(0, '添加失败');
    }


    /**
     * 添加打卡记录
     */
    public function addClassNote(Request $request)
    {
        try{
            $openid = $request->openid;
            $params = $request->only(['class_id','content']);
            $class_id = $params['class_id'];
            if(!$class_id){
                fun_respon(0, '网络繁忙！!');
            }

            unset($params['class_id']);

            $punch_info = e_class::where(['id'=>$class_id])->first();
            if(!$punch_info){
                fun_respon(0, '课程不存在!');
            }
            DB::beginTransaction();
            $params['user_id'] = $openid;
            $params['content'] = $params['content']?$params['content']:'';
            $params['is_valid'] = 1;
            $res = e_user_note_info::insertGetId($params);
            if(!$res){
                throw new Exception('添加用户记录失败！');
            }

            $data['user_id'] = $openid;
            $data['e_class_id'] = $class_id;
            $data['e_user_note_id'] = $res;
            $data['is_valid'] = 1;
            $data['created_at'] = date('Y-m-d H:i:s',time());
            $ress = e_user_class_record::insert($data);
            if(!$ress){
                throw new Exception('添加发布记录失败！');
            }
            /*//添加积分
            $before_bonus = $bonus;
            $change_bonus = 5;
            $after_bonus = $before_bonus+$change_bonus;
            $status = 1;
            $type = 1;
            add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type);
            //更新用户的状态
            $user_res = user::where(['openid'=>$openid])->update(['bonus'=>$after_bonus]);
            if(!$user_res){
                throw new Exception('更新用户信息失败！');
            }
            //修改删除记录 这种状态是删除自己创建的打卡
            if($punch_info->user_id == $openid && $punch_info->is_del == 1){
                $result = punch_activity::where(['id'=>$punch_id])->update(['is_del'=>0]);
                if(!$result){
                    throw new Exception('修改活动记录失败！');
                }
            }
            user_punch_record::where(['punch_ac_id'=>$punch_id,'user_id'=>$openid])->update(['is_del'=>0]);*/

            DB::commit();
            fun_respon(1, '添加记录成功');
        }catch (\Exception $ex){
            DB::rollback();
            fun_respon(0, '添加失败'.$ex->getMessage().$ex->getLine());
        }

    }

    /**
     * @param Request $request
     * 列表
     */
    public function classList(Request $request){
        $where = ['status'=>1,'is_valid'=>1];
        $punch_info = e_class::where($where)->orderBy('hot','DESC')->get();
        if ($punch_info){
            foreach ($punch_info as &$v){
                $res = e_user_note_info::leftJoin('e_user_class_record','e_user_note_info.id','=','e_user_class_record.e_user_note_id')->where(['e_user_class_record.e_class_id'=>$v['id']])->groupBy('e_user_note_info.user_id')->get();
                $v['join_num'] = count($res);
            }
            $data['list'] = $punch_info;
            //$data['banner'] = ['image_url'=>'http://file.ucloud.osv.cn/2018/07/26/6IeObAhQdC8UCmi1Qw5d.png','appid'=>'','path'=>'pages/index/index/'];
            $data['banner'] = ['image_url'=>'https://file.ucloud.osv.cn/2018/09/17/ArsFk0ml9jK1Ra6dfYjr.png','appid'=>'','path'=>'pages/index/index/'];
            fun_respon(1, $data);
        }
        fun_respon(0, '暂无数据');
    }


    /**
     * @param Request $request
     * 课程详情
     */
    public function calssDetail(Request $request)
    {
        $openid = $request->openid;
        $class_id = $request->json('class_id');
        if(!$class_id){
            fun_respon(0, '缺少参数');
        }
        $class_info = e_class::where(['id'=>$class_id])->first();
        if(!$class_info){
            fun_respon(0, '暂无数据');
        }
        $note_info = e_user_note_info::leftJoin('e_user_class_record','e_user_note_info.id','=','e_user_class_record.e_user_note_id')->leftJoin('e_class','e_class.id','=','e_user_class_record.e_class_id')->leftJoin('e_user','e_user.openid','=','e_user_class_record.user_id')->orderBy('e_user_note_info.created_at','DESC')->take(2)->where(['e_user_class_record.e_class_id'=>$class_id])->get(['e_class.title','e_user_note_info.content','e_user_note_info.created_at','e_user_class_record.e_class_id','e_user_class_record.e_user_note_id','e_user.avatarUrl','e_user.nickName']);
        foreach ($note_info as &$value){
            $value['created_at'] = date('Y-m-d',strtotime($value['created_at']));
        }
        $res = e_user_note_info::leftJoin('e_user_class_record','e_user_note_info.id','=','e_user_class_record.e_user_note_id')->where(['e_user_class_record.e_class_id'=>$class_id])->groupBy('e_user_note_info.user_id')->get();
        $class_info['join_num'] = count($res);
        $class_info['note_list'] = $note_info;
        fun_respon(1, $class_info);
    }


    /**
     * @param Request $request
     * 获取笔记列表
     */
    public function getNoteList(Request $request){
        $openid = $request->openid;
        $class_id = $request->json('class_id');
        $note_id = $request->json('note_id','');
        $page = $request->json('page',0);
        if(!empty($note_id)){
            $note_info = e_user_note_info::leftJoin('e_user_class_record','e_user_note_info.id','=','e_user_class_record.e_user_note_id')
                ->leftJoin('e_class','e_class.id','=','e_user_class_record.e_class_id')
                ->leftJoin('e_user','e_user.openid','=','e_user_class_record.user_id')
                ->where(['e_user_note_info.id'=>$note_id])
                ->first(['e_class.title','e_user_note_info.content','e_user_note_info.created_at','e_user_class_record.e_class_id','e_user_class_record.e_user_note_id','e_user.avatarUrl','e_user.nickName']);
            if(!$note_info){
                fun_respon(0, '暂无数据！');
            }
            //查询是否点赞
            $where = ['user_id'=>$openid,'user_note_info_id'=>$note_id,'status'=>1];
            $re = e_user_info_likes::where($where)->first();
            $note_info['is_like'] = $re?1:0;
            //点赞数量
            $like_num = $this->getLikes(['user_note_info_id'=>$note_id,'status'=>1]);
            $note_info['like_num'] = $like_num;
            $note_info['created_at'] = date('Y-m-d',strtotime($note_info['created_at']));
            fun_respon(1, [$note_info]);
        }
        $offset = ($page)*$this->pageSize;
        if(!$class_id){
            fun_respon(0, '缺少参数');
        }
        $class_info = e_class::where(['id'=>$class_id])->first();
        if(!$class_info){
            fun_respon(0, '数据错误！');
        }
        $note_info = e_user_note_info::leftJoin('e_user_class_record','e_user_note_info.id','=','e_user_class_record.e_user_note_id')
            ->leftJoin('e_class','e_class.id','=','e_user_class_record.e_class_id')
            ->leftJoin('e_user','e_user.openid','=','e_user_class_record.user_id')
            ->where(['e_user_class_record.e_class_id'=>$class_id])
            ->orderBy('e_user_note_info.created_at','DESC')
            ->take($this->pageSize)->skip($offset)
            ->get(['e_class.title','e_user_note_info.content','e_user_note_info.created_at','e_user_class_record.e_class_id','e_user_class_record.e_user_note_id','e_user.avatarUrl','e_user.nickName']);
        if(!$note_info){
            fun_respon(0, '暂无数据');
        }
        foreach ($note_info as &$v){
            //查询是否点赞
            $where = ['user_id'=>$openid,'user_note_info_id'=>$v['e_user_note_id'],'class_id'=>$v['e_class_id'],'status'=>1];
            $re = e_user_info_likes::where($where)->first();
            $v['is_like'] = $re?1:0;
            //查询点赞数量
            $where = ['user_note_info_id'=>$v['e_user_note_id'],'class_id'=>$v['e_class_id'],'status'=>1];
            $like_num = $this->getLikes($where);
            $v['like_num'] = $like_num?$like_num:0;
            $v['created_at'] = date('Y-m-d',strtotime($v['created_at']));
        }
        fun_respon(1, $note_info);
    }


    /**
     * @param $where
     * @return int
     * h获取笔记的点赞数量
     */
    private function getLikes($where){
        $like_num = e_user_info_likes::where($where)->count();
        return  $like_num?$like_num:0;
    }


    public function getJoinNum(Request $request){
        $punch_id = $request->json('punch_id');
        $joiner = $this->joinnum($punch_id);
        if($joiner){
            fun_respon(1, $joiner);
        }else{
            fun_respon(0, '暂无数据');

        }
    }


    /**
     * @param Request $request
     * 删除打卡
     */
    public function delPunch(Request $request){
        $punch_id = $request->json('punch_id');
        $openid = $request->openid;
        $punch_info = punch_activity::where(['id'=>$punch_id])->first();
        if(!$punch_info){
            fun_respon(0, '打卡活动不存在!');
        }
        if($punch_info->user_id == $openid){
            punch_activity::where(['id'=>$punch_id])->update(['is_del'=>1]);
        }
        $res = user_punch_record::where(['punch_ac_id'=>$punch_id,'user_id'=>$openid])->update(['is_del'=>1]);
        if($res){
            fun_respon(1, '删除成功！');
        }else{
            fun_respon(1, '删除失败！');
        }
    }

    private function joinnum($punch_id){
        /*$join_punch = user_punch_record::leftJoin('user','user_punch_record.user_id','=','user.openid')
            ->where(['user_punch_record.punch_ac_id'=>$punch_id,'user_punch_record.is_valid'=>1])->groupBy(['user_punch_record.user_id'])
            ->get(['avatarUrl']);*/
        return 0;
        return $join_punch;
    }

    /**
     * @param Request $request
     * 添加评论
     */
    public function addComments(Request $request){
        $punch_id = $request->json('punch_id');
        $share_info_id = $request->json('share_info_id');
        $to_user_id = $request->json('to_user_id');
        $content = $request->json('content');
        $openid = $request->openid;
        if(!$punch_id || !$share_info_id || !$content){
            fun_respon(0, '缺少信息!');
        }
        $punch_info = punch_activity::getOne($punch_id);
        if(!$punch_info){
            fun_respon(0, '打卡活动不存在!');
        }
        $arr = [
            'punch_id'=>$punch_id,
            'share_info_id'=>$share_info_id,
            'user_id'=>$openid,
            'to_user_id'=>$to_user_id?$to_user_id:0,
            'content'=>$content,
        ];
        $res = punch_comments::insert($arr);
        if($res){
            $data =[];
            if($to_user_id){
                $to_user_nickName = user::where(['id'=>$to_user_id])->first(['nickName']);
                $data['to_user_nickName'] = $to_user_nickName['nickName'];
            }else{
                $data['to_user_nickName'] = '';
            }
            $data['is_mine'] = 1;
            $user_nickName = user::where(['openid'=>$openid])->first(['id','nickName']);
            $data['user_nickName'] = $user_nickName['nickName'];
            $data['user_id'] = $user_nickName['id'];
            $data['content'] = $content;
            fun_respon(1, $data);
        }else{
            fun_respon(1, '评论失败！');
        }
    }


    /**
     * 生成带参数的二维码
     */
    public function makeqrcode(Request $request)
    {
        try {
            $punch_id = $request->json('id', 1);
            if ( empty($punch_id) ) {
                fun_respon(0, '缺少参数');
            }
            //pages/home/activity/activity?job_id=xx
            $param = $punch_id;
            WxSmallClient::qrcode($param);
        } catch (\Exception $ex) {
            //var_dump($ex->getMessage().$ex->getLine());
            fun_respon(0, '系统繁忙，请稍后再试！'.$ex->getMessage());
        }
    }




}
